/**
 * Created by Steven on 2018/1/7.
 */
import React, { Component } from 'react';
import {
  StyleSheet,
  FlatList,
  ActivityIndicator,
  View,
} from 'react-native';
import Item from '../components/Item.js';

const api = 'https://api.douban.com/v2/movie/in_theaters';


const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  row: {
    paddingHorizontal: 15,
  },
  loading: {
    marginTop: 100,
  },
});

export default class List extends Component {
  static navigationOptions = {
    title: '列表',
  };
  state ={
    movies: [],
    refreshing: false, // 控制refreshing的状态
    ready: false,
  }
  refreshing = false;// 判断函数是否在执行
  start = 0;// 起始下标
  count = 9;// 每次请求的数量
  fetchData = (start = 0, count = 9) => {
    if (this.refreshing) {
      return;
    }
    this.setState({
      refreshing: true,
    });
    this.refreshing = true;

    return fetch(`${api}?start=${start}&count=${count}`)
      .then((response) => response.text())
      .then((responseText) => {
        const json = JSON.parse(responseText);
        this.setState({
          refreshing: false,
        });
        console.log(json);
        this.refreshing = false;
        return json;
      })
      .catch((error) => {
        console.error(error);
      });
  };
  loadNewData = async () => {
    const jsonData = await this.fetchData(0, this.count);
    this.setState({
      movies: jsonData.subjects,
      ready: true,
    });
    this.start += this.count;
  };
  loadMoreData = async () => {
    const jsonData = await this.fetchData(this.start, this.count);
    if (jsonData)
    {
      const currentMovies = this.state.movies.concat(jsonData.subjects);
      this.start += this.count;
      this.setState({
        movies: currentMovies,
      });
    }
  }

  async componentDidMount() {
    this.loadNewData();
  }
  gotoDetail = (param) => {
    const { navigate } = this.props.navigation;
    navigate('Detail');
  }
  render() {
    const { movies, refreshing, ready } = this.state;
    return (
      <View style={styles.container}>
        {
          ready
            ?
            <FlatList
              keyExtractor={item => item.id}
              numColumns={3}
              data={movies}
              onRefresh={this.loadNewData}
              refreshing={refreshing}
              onEndReached={this.loadMoreData}
              onEndReachedThreshold={0}
              refreshing={refreshing}
              ListFooterComponent={() => {
                return refreshing &&
                  <ActivityIndicator size="large" />
              }}
              renderItem={({ item }) => {
                console.log(item);
                return (
                  <Item
                    text={item.title}
                    imageUrl={item.images.medium}
                    onPress={() => this.gotoDetail(item)}
                  />
                )
              }}
            />
            :
            <ActivityIndicator size="large" style={styles.loading} />
        }
      </View>
    );
  }
}